package com.huawei.crm.util;

import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Map.Entry;

/**
 * Excel模板工具类
 *
 * @author luohua
 * @date 2021/7/14
 */
public class ExcelUtils {

    /***
     * excel导出到response
     *
     * @param templateFile 模板文件地址
     * @param model       数据集合
     * @param fileName     目标文件名
     * @param response     输出流
     */
    public static void exportExcel(InputStream templateFile, Map<String, Object> model, String fileName,
                                   HttpServletResponse response) throws IOException {
        response.setHeader("Content-disposition",
                String.format("attachment; filename=\"%s\"", URLEncoder.encode(fileName, "UTF-8")));
        response.setContentType("application/octet-stream;charset=UTF-8");
        try {
            OutputStream os = response.getOutputStream();
            exportExcel(templateFile, model, os);

        } catch (IOException e) {
            throw e;
        }
    }

    /**
     * 导出excel到输出流中
     *
     * @param templateFile 模板文件
     * @param model        数据集合
     * @param os           输出流
     * @throws IOException
     */
    public static void exportExcel(InputStream templateFile, Map<String, Object> model, OutputStream os)
            throws IOException {
        try {
            Context context = new Context();
            if (!CollectionUtils.isEmpty(model)) {
                for (Entry<String, Object> data : model.entrySet()) {
                    context.putVar(data.getKey(), data.getValue());
                }
            }
            JxlsHelper.getInstance().processTemplate(templateFile, os, context);

        } catch (IOException e) {
            throw e;
        } finally {
            if (os != null) {
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    throw e;
                }
            }

            if (templateFile != null) {
                try {
                    templateFile.close();
                } catch (IOException e) {
                    throw e;
                }
            }
        }
    }

}
